package com.example.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Created by douyx on 2017/11/16.
 */
@SuppressWarnings("deprecation")
public class ExcelUtil {

	/**
     * 双表头Excel导出
     * 
     * @param sheetName sheet名
     * @param colList 数据列名
     * @param head1 表头1
     * @param head2 表头2（与colList的顺序一致）
     * @param info 数据
     * @return
     * @throws Exception
     */
    public static String writeExcel(String sheetName, List<String> colList, Map<String, Integer[]> head1,
            String[] head2, List<HashMap<String, Object>> info) throws Exception {
        if (colList.size() != head2.length) {
            throw new RuntimeException("列名个数不一致");
        }
        // 生成随机数
        int randomNum = (int) (Math.random() * 10000000);
        // 输出Excel路径
        String filePath = System.getProperty("java.io.tmpdir");
        if (filePath.endsWith(File.separator)) {
            filePath = System.getProperty("java.io.tmpdir") + randomNum + ".xls";
        } else {
            filePath = System.getProperty("java.io.tmpdir") + File.separator + randomNum + ".xls";
        }

        FileOutputStream fileOutStream = new FileOutputStream(filePath);

        // 创建Excel
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet(sheetName);
        sheet.createFreezePane(colList.size(), 1);

        // 表头式样
        HSSFCellStyle cellHeadStyle = workbook.createCellStyle();
        // 边框
        cellHeadStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellHeadStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cellHeadStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellHeadStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 居中
        cellHeadStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        // 内容式样
        HSSFCellStyle cellBodyStyle = workbook.createCellStyle();
        // 边框
        cellBodyStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellBodyStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cellBodyStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellBodyStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 居右
        cellBodyStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);

        // 填充表头1
        HSSFRow headerRow1 = sheet.createRow(0);
        for (Entry<String, Integer[]> headEntry : head1.entrySet()) {
            Integer[] regionCell = headEntry.getValue();
            HSSFCell headerCell = headerRow1.createCell(regionCell[0]);
            headerCell.setCellValue(new HSSFRichTextString(headEntry.getKey()));
            sheet.addMergedRegion(new CellRangeAddress(0, (short) regionCell[0].intValue(), 0, (short) regionCell[1].intValue()));
            headerCell.setCellStyle(cellHeadStyle);
        }
        // 填充表头2
        HSSFRow headerRow2 = sheet.createRow(1);
        for (int i = 0; i < colList.size(); i++) {
            HSSFCell headerCell = headerRow2.createCell(i);
            headerCell.setCellValue(new HSSFRichTextString(head2[i]));
            headerCell.setCellStyle(cellHeadStyle);
        }
        // 填充内容
        for (int i = 2; i <= info.size() + 1; i++) {
            HSSFRow bodyRow = sheet.createRow(i);
            for (int j = 0; j < colList.size(); j++) {
                HSSFCell bodyCell = bodyRow.createCell(j);
                Object val = info.get(i - 2).get(colList.get(j));
                if (val instanceof BigDecimal) {
                    bodyCell.setCellValue(new HSSFRichTextString(((BigDecimal) val).toPlainString()));
                } else {
                    bodyCell.setCellValue(new HSSFRichTextString((String) val));
                }
                bodyCell.setCellStyle(cellBodyStyle);
            }
        }

        workbook.write(fileOutStream);
        fileOutStream.flush();
        fileOutStream.close();
        return filePath;
    }

    /**
     * 生成Excel
     * 
     * @param sheetName sheet名
     * @param colList 数据列名
     * @param head 表头（与colList的顺序一致）
     * @param info 数据
     * @return
     * @throws Exception
     */
    public static String writeExcel(String sheetName, List<String> colList, String[] head,
            List<HashMap<String, Object>> info) throws Exception {
        FileOutputStream fileOutStream = null;
        String filePath = "";
        try {
            if (colList.size() != head.length) {
                throw new RuntimeException("列名个数不一致");
            }
            // 生成随机数
            int randomNum = (int) (Math.random() * 10000000);
            // 输出Excel路径
            filePath = System.getProperty("java.io.tmpdir");
            if (filePath.endsWith(File.separator)) {
                filePath = System.getProperty("java.io.tmpdir") + randomNum + ".xls";
            } else {
                filePath = System.getProperty("java.io.tmpdir") + File.separator + randomNum + ".xls";
            }

            fileOutStream = new FileOutputStream(filePath);

            // 创建Excel
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet(sheetName);
            sheet.createFreezePane(colList.size(), 1);

            HSSFRow headerRow = sheet.createRow(0);
            // 填充表头
            for (int i = 0; i < colList.size(); i++) {
                HSSFCell headerCell = headerRow.createCell(i);
                headerCell.setCellValue(new HSSFRichTextString(head[i]));
            }
            // 填充内容
            for (int i = 1; i <= info.size(); i++) {
                HSSFRow bodyRow = sheet.createRow(i);
                for (int j = 0; j < colList.size(); j++) {
                    HSSFCell bodyCell = bodyRow.createCell(j);
                    bodyCell.setCellValue(new HSSFRichTextString(String.valueOf(info.get(i - 1).get(colList.get(j)))));
                }
            }

            workbook.write(fileOutStream);

        }finally {
            if(fileOutStream != null){
                try{
                    fileOutStream.flush();
                    fileOutStream.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return filePath;
    }


    public static  List<List<Object>> getListByExcel(InputStream in, String fileName) throws Exception{
        List<List<Object>> list = null;

        //创建Excel工作薄
        Workbook work = getWorkbook(in,fileName);
        if(null == work){
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;

        list = new ArrayList<List<Object>>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if(sheet==null){continue;}

            //遍历当前sheet中的所有行
            for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum()+1; j++) {
                row = sheet.getRow(j);
                if(row==null||row.getFirstCellNum()==j){continue;}

                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    li.add(getCellValue(cell));
                }
                list.add(li);
            }
        }
//        work.close();
        return list;
    }

    private final static String excel2003L =".xls";    //2003- 版本的excel
    private final static String excel2007U =".xlsx";   //2007+ 版本的excel

    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public static  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if(excel2003L.equals(fileType)){
            wb = new HSSFWorkbook(inStr);  //2003-
        }else if(excel2007U.equals(fileType)){
            wb = new XSSFWorkbook(inStr);  //2007+
        }else{
            throw new Exception("解析的文件格式有误！");
        }
        return wb;
    }

    /**
     * 描述：对表格中数值进行格式化
     * @param cell
     * @return
     */
    public static  Object getCellValue(Cell cell){
        Object value = null;
        DecimalFormat df = new DecimalFormat("0");  //格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化
        DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字
        //单位个为空
        if(cell==null){
            return "";
        }
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if("General".equals(cell.getCellStyle().getDataFormatString())){
                    value = df.format(cell.getNumericCellValue());
                }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
                    value = sdf.format(cell.getDateCellValue());
                }else{
                    value = df2.format(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            default:
                break;
        }
        return value;
    }
}
